import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/models/chat_message/xindong_signal_message.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/tab_chats/xindong_chat_message_type.dart';
import 'package:xindong/utils/xindong_conversion_util.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

import 'xindong_liaotian_message_text_cell.dart';
import 'xindong_liaotian_system_tips.dart';

class XinDongLiaoTianMessageCustomSignaling extends StatelessWidget {
  final V2TimMessage message;
  final double maxWidth;
  final XinDongChatMessageType chatMessageType;

  const XinDongLiaoTianMessageCustomSignaling(
      {Key? key, required this.message, required this.maxWidth, required this.chatMessageType})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    try {
      String data = message.customElem!.data!;
      Map<String, dynamic> signalDataMap = json.decode(data);
      int actionType = signalDataMap["actionType"];
      String inviter = signalDataMap["inviter"];
      XinDongSignalMessage model = XinDongConversionUtil.decodeJsonToSignalClass(signalDataMap["data"]);
      mDebugPrint("信令消息 $actionType ${model.type} ${model.isCallEnd}");
      String text = "";
      switch (actionType) {
        case XinDongSignalActionType.invite:
          {
            String callType = model.type == XinDongCallType.audioCall
                ? "语音通话"
                : model.type == XinDongCallType.videoCall
                    ? "视频通话"
                    : "";
            if (model.isCallEnd) {
              return const SizedBox(); // 结束显示使用12300代替
            } else {
              text = "发起$callType";
            }
          }
          break;
        case XinDongSignalActionType.cancel:
          text = "取消通话";
          break;
        case XinDongSignalActionType.reject:
          text = "${model.isBusy ? "正在通话中，系统自动" : ""}拒绝了通话";
          break;
        case XinDongSignalActionType.timeout:
          text = "未接听";
          break;
        case XinDongSignalActionType.accept:
          return const SizedBox();
      }
      // 是聊天类型，添加textElem属性显示
      if (chatMessageType.isChatTypeSignaling(message)) {
        message.elemType = MessageElemType.V2TIM_ELEM_TYPE_TEXT;
        message.textElem = V2TimTextElem(text: text);
        return XinDongLiaoTianMessageText(message: message, maxWidth: maxWidth);
      }
      return XinDongLiaoTianSystemTips(text: text);
    } catch (e) {
      mCatchPrint(e);

      /// 版本不兼容
      return const XinDongLiaoTianSystemTips(text: kTextUpdateVersion);
    }
  }
}
